package sc.display;

import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;

import sc.util.DisplayData;
import sc.util.StockSummaryReader;
import sc.writable.IntermediateData.Type;

/**
 * Main frame to display stocks and their scores. A double click on a stock
 * opens detailed informations.
 * 
 * @author Quentin Rossé
 *
 */
@SuppressWarnings("serial")
public class MainFrame extends JFrame{

	private static final int DEFAULT_SIZE_X = 800;
	
	private static final int DEFAULT_SIZE_Y = 600;
	
	private JTable table;
	
	private MainTableModel tableModel;
	
	
	public MainFrame(DisplayData data){	
		setTitle("Stocks");
        setSize(DEFAULT_SIZE_X, DEFAULT_SIZE_Y);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new GridLayout(1, 0));
        
        //init table
		tableModel = new MainTableModel(getColumnNames(), 
				                        data.getStocks(), 
				                        data.getDetails());
		tableModel.updateTableData();
		table = new JTable(tableModel);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.setAutoCreateRowSorter(true);

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
        
        //clicks on the table
        table.addMouseListener(new MouseAdapter() {
        	public void mouseClicked(MouseEvent mouseEvent) {
        		if(mouseEvent.getClickCount() > 1){
        			tableModel.openDetails(table.convertRowIndexToModel(table.getSelectedRow()));	
        		}
        	}
		});
        
        setVisible(true);
	}
	
	
	private String[] getColumnNames(){
		Type[] t = Type.values();
		String[] columnNames = new String[t.length+1];
		
		columnNames[0] = "Stock Symbol";
		for(int i=0; i<t.length; i++)
			columnNames[i+1] = t[i].toString();
		
		return columnNames;
	}
	
	
	public static void main(String[] args) throws IOException{
		System.out.println("HDFS config file : " + args[0]);
		System.out.println("inputFiles : " + args[1]);
		
		Configuration conf = new Configuration();
		conf.addResource(new Path(args[0]));
		
		new MainFrame(StockSummaryReader.readStockSummary(args[1], conf));
	}
}
